package dotdashdot.bradz.trendsettr;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.Date;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.androidplot.xy.SimpleXYSeries;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYSeries;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class FragmentItemDetail extends Fragment {
	public static final String ARG_ITEM_ID = "item_id";
	private String mItem;
	private ClassGraphInfo info;
	private ClassNetworkHelper helper;
	private ClassFormatGraph format;
	private Context self;
	private ClassFonts fonts;
	private ClassUberLogger logger;
	private boolean pop_up_showing;
	
	Handler myHandler = new Handler() {

  	    @Override
  	    public void handleMessage(Message msg) {
  	        switch (msg.what) {
  	        case 1:
  	        	construct_graph();
  	            break;
  	        case 6:
	        	report_sent_confirm();
	        	break;
  	        default:
  	            break;
  	        }
  	    }
  	};
	
	public FragmentItemDetail() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		logger = new ClassUberLogger("FragmentItemDetail");

		if (getArguments().containsKey(ARG_ITEM_ID)) {
			mItem = getArguments().getString(ARG_ITEM_ID);
		}
		logger.info("OnCreate Finished");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		logger.info("Creating View");
		
		View rootView = inflater.inflate(R.layout.graph,container, false);
		
		self = this.getActivity();
		fonts = new ClassFonts(self.getAssets());
		
		helper = new ClassNetworkHelper(this.getActivity(),((ApplicationGlobalVars) this.getActivity().getApplication()));
		
		// Show the dummy content as text in a TextView.
		if (mItem != null) {
			
			logger.info("Click was a valid list item");
			
			//((Button) rootView.findViewById(R.id.top_navigation_button)).setText(mItem);
			((Button) rootView.findViewById(R.id.top_navigation_button)).setText("Trend Details");
			
			info = new ClassGraphInfo(new ArrayList<ClassGraphData>(), "", mItem, rootView);
			//Can't be passing empty arrays to this bitch
        	XYPlot dynamic_plot = (XYPlot) info.v.findViewById(R.id.trend_plot);
	    	format = new ClassFormatGraph(dynamic_plot, getResources().getColor(R.color.navigation_color));
	    	
	    	logger.info("Receiving graph info from server");
	    	
	    	create_report_button(rootView);
	    	
			helper.get_all_from_network_trend_history(info, myHandler);
			
		}

		return rootView;
	}
	
	@Override
	public void onStart(){
		super.onStart();
		format_nav_tab();
		logger.info("OnStart finished");
	}
	
	private void format_nav_tab(){
		((Button) this.getActivity().findViewById(R.id.top_navigation_button)).setTypeface(fonts.get_font("cond_medium"));
		((TextView) this.getActivity().findViewById(R.id.see_trend_details_meta_title)).setTypeface(fonts.get_font("cond_bold"));
		((TextView) this.getActivity().findViewById(R.id.see_trend_details_meta_title)).setSelected(true);
		
		((TextView) this.getActivity().findViewById(R.id.header_gender)).setTypeface(fonts.get_font("cond_bold"));
		((TextView) this.getActivity().findViewById(R.id.header_age)).setTypeface(fonts.get_font("cond_bold"));
		((TextView) this.getActivity().findViewById(R.id.header_location)).setTypeface(fonts.get_font("cond_bold"));
		
		((TextView) this.getActivity().findViewById(R.id.footer_gender)).setTypeface(fonts.get_font("cond_light"));
		((TextView) this.getActivity().findViewById(R.id.footer_age)).setTypeface(fonts.get_font("cond_light"));
		((TextView) this.getActivity().findViewById(R.id.footer_location)).setTypeface(fonts.get_font("cond_light"));
		logger.info("Nav tab formatted");
	}
	
	public void construct_graph(){
		logger.info("Reseting new layout");
        
        ArrayList<Number> date_list = new ArrayList<Number>(Arrays.asList(info.get_date_array()));
        ArrayList<Number> value_list = new ArrayList<Number>(Arrays.asList(info.get_vote_array()));
        
        if(info.dates_same() && date_list.size() > 0 && value_list.size() > 0){
        	Number date = date_list.get(0);
        	date = (Number)(date.intValue() - 1);
        	date_list.add(date);
        	value_list.add(value_list.get(0));
        }
        
        XYSeries series2 = new SimpleXYSeries(date_list, value_list,"");

        logger.info("Printing graph info");
        for(Number num: date_list){
        	logger.info("Date: " + num);
        }
        for(Number num: value_list){
        	logger.info("value: " + num);
        }
        logger.info("Done printing graph info");
        
        //Just error checking. This should always be true.
        if(series2.size()>0){
        	
        	logger.info("Drawing graph");
        	
	    	format.add_series(series2);
	    	
	    	format.format_date(info.dates_same());

	    	TextView title_text = ((TextView) info.v.findViewById(R.id.see_trend_details_meta_title));
	    	title_text.setText(mItem);
	    	
	    	//Doubles the marquee scrolling speed
			try {
				Field f = title_text.getClass().getDeclaredField("mMarquee");
		        f.setAccessible(true);
		        Object marquee = f.get(title_text);
		    	if(marquee != null){
		    		Field mf = marquee.getClass().getDeclaredField("mScrollUnit");
		    		mf.setAccessible(true);
		    		float newSpeed = mf.getFloat(marquee) * 4;
		    		mf.setFloat(marquee, newSpeed);
		    	}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				logger.error(e.getMessage());
			}
	    	
	        ((TextView) info.v.findViewById(R.id.see_trend_details_meta_title)).setText(mItem);
	        
			try {
				Map<String, Integer> map = new HashMap<String, Integer>();
				map.put("gender", R.id.footer_gender);
				map.put("age", R.id.footer_age);
				map.put("location", R.id.footer_location);
				map.put("picture", R.id.creator_picture);
				
		        String buffer = ((ApplicationGlobalVars) this.getActivity().getApplication()).get_buffer();
		        
		        logger.info(buffer);
		        
		        JSONObject jObject = new JSONObject(buffer.trim());
		        Iterator<?> keys = jObject.keys();
	
		        while( keys.hasNext() ){
		        	String key = (String)keys.next();
		        	logger.info("Key: " + key);
		        	if(map.containsKey(key)){
		        		if(key.equals("picture")){
		        			logger.info("Picture");
		        			new DownloadImageTask((ImageView) info.v.findViewById(map.get(key))).execute(String.valueOf(jObject.get(key)));
		        		}else{
		        			logger.info("Text");
		        			((TextView) info.v.findViewById(map.get(key))).setText(String.valueOf(jObject.get(key)));
		        		}
		        	}
		        }
		        
		        //((TextView) info.v.findViewById(R.id.see_trend_details_meta)).setText(meta_buffer);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        
	        logger.info("Invalidating previous graph");
	        
	        info.v.invalidate();
        }
	}
	private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
	    ImageView bmImage;

	    public DownloadImageTask(ImageView bmImage) {
	        this.bmImage = bmImage;
	    }

	    protected Bitmap doInBackground(String... urls) {
	        String urldisplay = urls[0];
	        Bitmap mIcon11 = null;
	        try {
	            InputStream in = new java.net.URL(urldisplay).openStream();
	            mIcon11 = BitmapFactory.decodeStream(in);
	        } catch (Exception e) {
	            Log.e("Error", e.getMessage());
	            e.printStackTrace();
	        }
	        return mIcon11;
	    }

	    protected void onPostExecute(Bitmap result) {
	        bmImage.setImageBitmap(result);
	    }
	}
	private void create_report_button(final View parent_view){
		
		final Button btnOpenPopup = (Button) info.v.findViewById(R.id.report_trend);
		pop_up_showing = false;
        btnOpenPopup.setOnClickListener(new Button.OnClickListener(){

		   @Override
		   public void onClick(View arg0) {
			   if(!pop_up_showing){
						   
				     //LayoutInflater layoutInflater  = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);  
					 LayoutInflater layoutInflater = (LayoutInflater)getActivity().getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					 final View popupView = layoutInflater.inflate(R.layout.report_popup, null);  
		             final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT,  LayoutParams.WRAP_CONTENT);  
		             Button btnDismiss = (Button) popupView.findViewById(R.id.submit_report);
		             btnDismiss.setOnClickListener(new Button.OnClickListener(){
					     @Override
					     public void onClick(View v) {
					    	 popupWindow.dismiss();
					    	 pop_up_showing = false;
					    	 
					    	 /*
					    	  * var new_report = {
								trendName: JSON.parse(req.headers.json)["trendName"],
								created: new Date().getTime(),
								createdBy: user,
								report: JSON.parse(req.headers.json)["report"]}
					    	  */
				    	     // get selected radio button from radioGroup
				             int selectedId = ((RadioGroup) popupView.findViewById(R.id.radio_report)).getCheckedRadioButtonId();
				             String report_text = ((RadioButton) popupView.findViewById(selectedId)).getText().toString();

					    	 ArrayList<NameValuePair> post_data = new ArrayList<NameValuePair>();
						     post_data.add(new BasicNameValuePair("trendName", mItem));
						     post_data.add(new BasicNameValuePair("report", report_text));
					    	 helper.post_network(post_data, "/report", myHandler);
					     }
					 });
		               
		             //popupWindow.setFocusable(true);
		             popupWindow.setOutsideTouchable(true);
		             
		             Display display = getActivity().getWindowManager().getDefaultDisplay();
		             
		             Point size = new Point(display.getWidth(),display.getHeight());
		             popupWindow.showAtLocation(parent_view, Gravity.CENTER, 0, 0);
		             popupWindow.update(size.x/50, size.y/20, 7*size.x/10, 6*size.y/10);
		             popupWindow.setOutsideTouchable(false);
		             
		             //Dismiss the popup if the parent is clicked
		     		 parent_view.setOnClickListener(new View.OnClickListener() {
		    			
		    			@Override
		    			public void onClick(View v) {
		    				// TODO Auto-generated method stub
		    				popupWindow.dismiss();
		    				pop_up_showing = false;
		    			}
		     		 });
		     		pop_up_showing = true;
				   }
		   }
        });
    }
	public void report_sent_confirm(){
		Toast.makeText(self, "Report Sent Successfully!", Toast.LENGTH_LONG).show();
	}
}
